import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken } from '@/utils/auth'
import baseURL from './baseURL'

// create an axios instance
const service = axios.create({
  // baseURL: baseURL.webUrl,
  baseURL: '',
  timeout: 10 * 6000 // request timeout
})

service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  response => {
    const res = response.data
    const url = response.config.url
    if (url.includes('api.php')) {
      // console.log(res)
      return res
    } else if (!res.success) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  async error => {
    let { response } = JSON.parse(JSON.stringify(error))
    let { data, status } = response || {};
    console.log(data, response)
    if (status == 401) {
      await store.dispatch('user/logout')
      router.push('/login');
      Message({
        message: '认证已过期请重新登录',
        type: 'error'
      })
    } else {
      let mag = data ? data : error.message || '接口异常'
      Message({
        message: mag,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
  }
)

export default service
